package com.cloud.code.反射;

import lombok.SneakyThrows;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 反射测试类
 */
public class Test {

    @SneakyThrows
    public static void main(String[] args) {
        Dog dog = new Dog();
        Class aClass = dog.getClass();

        Class dogClass = Dog.class;

        Class forName = Class.forName("com.cloud.code.反射.Dog");

        System.out.println(aClass == dogClass);
        System.out.println(aClass == forName);
        System.out.println(dogClass == dogClass);

        //获取所有属性
        Field[] declaredFields = forName.getDeclaredFields();
        Arrays.stream(declaredFields).forEach(tem -> System.out.println(tem));
        System.out.println("-------------------------");
        //获取所有方法
        Method[] declaredMethods = forName.getDeclaredMethods();
        Arrays.stream(declaredMethods).forEach(System.out::println);
        System.out.println("-------------------------");
        //获取所有构造方法
        Constructor[] declaredConstructors = forName.getDeclaredConstructors();
        Arrays.stream(declaredConstructors).forEach(System.out::println);

        Object newInstance = forName.getConstructor().newInstance();

        Method setName = forName.getMethod("setName", String.class);
        Method setAge = forName.getMethod("setAge", int.class);
        setAge.invoke(newInstance,13);
        Object invoke = setName.invoke(newInstance, "小狗");
        Method getName = forName.getMethod("getName");

        Field name = forName.getField("name");
        name.set(newInstance,"xiaogou");

        Object invoke1 = getName.invoke(newInstance);
        System.out.println(invoke1.toString());


        //获取私有方法执行
        Method getAge = forName.getDeclaredMethod("getAge");
        getAge.setAccessible(true);
        Object invoke2 = getAge.invoke(newInstance);
        System.out.println(invoke2);

        //获取注解
        Annotation[] annotations = forName.getAnnotations();
        System.out.println(annotations.toString());
        Arrays.stream(annotations).forEach(System.out::println);

    }

    @SneakyThrows
    @org.junit.Test
    public void test(){
        List<Dog> list = new ArrayList<>();
        list.add(new Dog());
        list.getClass().getMethod("add",Object.class).invoke(list,123);

        System.out.println(list);



    }
}
